<template>
  <s-layout :title="product.name || '产品详情'">
    <view class="detail-container">
      <scroll-view scroll-y class="content-scroll">
        <!-- 商品主图 -->
        <image class="product-main-image" :src="product.image" mode="widthFix" />

        <!-- 商品信息 -->
        <view class="product-info-card">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-desc">{{ product.description }}</view>
          <view class="product-price">¥{{ currentPrice }}</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-card" v-if="product.specs && product.specs.length > 0">
          <view class="spec-group" v-for="spec in product.specs" :key="spec.name">
            <view class="spec-group-header">
              <view class="spec-group-name">
                {{ spec.name }}
                <text class="spec-count">({{ spec.options.length }} 个可选)</text>
              </view>
            </view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="option in spec.options"
                :key="option.name"
                :class="{ active: isOptionSelected(spec, option) }"
                @click="selectSpec(spec, option)"
              >
                <view class="option-name">{{ option.name }}</view>
                <view class="option-price" v-if="option.price && option.price > 0">
                  +¥{{ option.price }}
                </view>
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="price-section">
          <text>¥</text>
          <text class="price-value">{{ currentPrice }}</text>
        </view>
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { 
  getSpecKey, 
  getOptionKey, 
  findOption, 
  safeParseFloat, 
  buildSpecsText, 
  parsePrice,
  parseOriginalPrice,
  buildFullSelectedSpecs,
  stripHtmlTags
} from './common/product-utils.js';

const cateringStore = sheep.$store('catering');

const product = reactive({
  id: 0,
  name: '',
  image: '',
  description: '',
  basePrice: 0,
  originalPrice: 0,
  specs: [],
  skuList: []  // ✅ 新增：SKU列表
});

const selectedSpecs = reactive({});

onLoad(async (options) => {
  const passedProductId = options.productId || options.id;
  const passedShopId = options.shopId;

  if (!passedProductId) {
    uni.showToast({ title: '缺少商品信息', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }
  
  const store = cateringStore.storeInfo;
  const shopId = passedShopId || (store && (store.shopId || store.id));
  if (!shopId) {
    uni.showToast({ title: '请先选择门店', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }

  console.log('【瑞幸】加载商品详情:', { productId: passedProductId, shopId });
  
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await sheep.$api.catering.getProductDetail(passedProductId, shopId);
    uni.hideLoading();
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      parseProductData(res.data, options);
    } else {
      uni.showToast({ title: '加载商品失败', icon: 'none' });
      setTimeout(() => sheep.$router.back(), 1500);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【瑞幸】加载商品详情失败:', error);
    uni.showToast({ title: '加载商品失败', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
  }
});

// 解析瑞幸商品数据
function parseProductData(apiData, options) {
  // 基础信息
  product.id = apiData.product_id || apiData.productId || options.productId;
  product.name = apiData.product_name || apiData.productName || options.name || '';
  product.image = apiData.product_img || apiData.productImg || '';
  // ✅ 处理HTML格式的描述
  const rawDesc = apiData.product_description || apiData.productDescription || '';
  product.description = stripHtmlTags(rawDesc);
  product.basePrice = parsePrice(apiData);
  product.originalPrice = parseOriginalPrice(apiData);

  console.log('【瑞幸】售价:', product.basePrice, '原价:', product.originalPrice);

  const details = apiData.details || apiData;
  
  // 解析瑞幸规格（使用 ingredients 字段）
  if (details.specifications) {
    product.specs = details.specifications.map(spec => ({
      name: spec.name,
      options: (spec.ingredients || []).map(ing => ({
        name: ing.name,
        price: safeParseFloat(ing.price),
        checked: ing.checked || false
      }))
    }));
    console.log('【瑞幸】解析后的规格:', JSON.stringify(product.specs, null, 2));
  }

  // ✅ 解析 SKU 列表
  if (details.sku_infos) {
    product.skuList = details.sku_infos.map(sku => ({
      code: sku.code,
      values: sku.values || []
    }));
    console.log('【瑞幸】SKU列表:', product.skuList.length, '个');
    console.log('【瑞幸】SKU详情:', JSON.stringify(product.skuList, null, 2));
  }

  // 初始化默认选中
  initializeDefaultSelection();
}

// 初始化默认选中
function initializeDefaultSelection() {
  product.specs.forEach(spec => {
    if (!spec.options || spec.options.length === 0) return;
    
    const defaultOption = spec.options.find(opt => opt.checked) || spec.options[0];
    selectedSpecs[getSpecKey(spec)] = getOptionKey(defaultOption);
  });
}

// 判断选项是否被选中
function isOptionSelected(spec, option) {
  return selectedSpecs[getSpecKey(spec)] === getOptionKey(option);
}

// 选择规格
function selectSpec(spec, option) {
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  selectedSpecs[specKey] = optionKey;
  console.log('【瑞幸】当前已选规格:', JSON.parse(JSON.stringify(selectedSpecs)));
}

// ✅ 查找匹配的 SKU
function findMatchedSKU() {
  if (!product.skuList || product.skuList.length === 0) {
    console.error('【瑞幸】SKU列表为空');
    return null;
  }
  
  // 将 selectedSpecs 转换为 { "温度": "热", "糖度": "少甜" } 格式
  const selectedMap = {};
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (selectedOptionKey) {
      selectedMap[specKey] = selectedOptionKey;
    }
  });
  
  console.log('【瑞幸】查找SKU，当前选择:', selectedMap);
  console.log('【瑞幸】SKU总数:', product.skuList.length);
  
  // 查找匹配的 SKU
  const matchedSku = product.skuList.find((sku, index) => {
    console.log(`【瑞幸】检查SKU[${index}]:`, sku.code);
    
    // 检查 SKU 的所有规格是否匹配
    const isMatch = sku.values.every(skuValue => {
      const specName = skuValue.name;  // 如 "温度"
      const specValue = skuValue.spec_name;  // 如 "热"
      const selected = selectedMap[specName];  // 用户选择的值
      const match = selected === specValue;
      
      console.log(`  规格匹配检查: ${specName} - SKU期望: ${specValue}, 用户选择: ${selected}, 匹配: ${match}`);
      return match;
    });
    
    console.log(`  SKU[${index}] ${sku.code} 最终匹配结果:`, isMatch);
    return isMatch;
  });
  
  if (matchedSku) {
    console.log('✅【瑞幸】找到匹配SKU:', matchedSku.code);
  } else {
    console.error('❌【瑞幸】未找到匹配的SKU');
    console.error('当前选择:', selectedMap);
    console.error('可用SKU列表:', product.skuList.map(s => ({
      code: s.code,
      values: s.values.map(v => `${v.name}:${v.spec_name}`).join(', ')
    })));
  }
  
  return matchedSku;
}

// 计算当前价格
const currentPrice = computed(() => {
  let finalPrice = product.basePrice;
  
  // 规格加价
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (!selectedOptionKey) return;
    
    const option = findOption(spec, selectedOptionKey);
    if (option?.price) {
      finalPrice += option.price;
    }
  });
  
  return finalPrice.toFixed(2);
});

// 加入购物车
function addToCart() {
  // ✅ 查找匹配的 SKU
  const matchedSku = findMatchedSKU();
  if (!matchedSku) {
    uni.showToast({ title: '请选择完整的规格', icon: 'none' });
    return;
  }
  
  // 构建完整的规格对象（包含 id 和 linkId）
  const fullSelectedSpecs = buildFullSelectedSpecs(product.specs, selectedSpecs);
  
  const cartItem = {
    id: product.id,
    name: product.name,
    image: product.image,
    price: parseFloat(currentPrice.value),
    originalPrice: product.originalPrice,
    skuId: matchedSku.code,  // ✅ 保存 SKU code
    selectedSpecs: fullSelectedSpecs,
    specsText: buildSpecsText(product.specs, selectedSpecs),
    brandOt: 16,  // ✅ 瑞幸咖啡品牌类型
  };

  console.log('【瑞幸】加入购物车 - 售价:', cartItem.price, '原价:', cartItem.originalPrice);
  console.log('【瑞幸】SKU:', matchedSku.code, '规格数据:', JSON.stringify(fullSelectedSpecs, null, 2));
  cateringStore.addToCart(cartItem);

  uni.showToast({ title: '已加入购物车', icon: 'success' });
  setTimeout(() => sheep.$router.back(), 1000);
}
</script>

<style lang="scss" scoped>
@import './common/product-detail.scss';

// 瑞幸特有样式
.spec-group-name {
  .spec-count {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}
</style>

